package repository

import (
	"context"
	"gitee.com/kristas/booting-go/framework"
	"gitee.com/kristas/booting-go/framework/core/statement/types"
	"gitee.com/kristas/booting-go/framework/data"
	"gitee.com/kristas/booting-go/framework/data/tk"
	. "gitee.com/kristas/booting-go/framework/data/tk/example"
	"gitee.com/kristas/booting-go/internal/demo/model"
	"gitee.com/kristas/booting-go/plugin/gorm_plugin"
)

func init() {
	framework.Component(
		new(AccountRepositoryImpl),
		tk.NewMapper("application.datasource", "account"),
		gorm_plugin.NewDB("application.datasource", "account"),
	)
}

type AccountRepository interface {
	data.Repository
	GetByUserName(ctx context.Context, username string) (*model.Account, error)
	GetList(ctx context.Context) ([]*model.Account, error)
	Update(ctx context.Context, account *model.Account) (*model.Account, error)
}

type AccountRepositoryImpl struct {
	types.Repository `table:"account"`
	Mapper           *tk.Mapper      `wire:"tk_mapper:application.datasource@account"`
	DB               *gorm_plugin.DB `wire:"gorm_db:application.datasource@account"`
}

func (r *AccountRepositoryImpl) GetByUserName(ctx context.Context, username string) (*model.Account, error) {
	var m = &model.Account{}
	example := NewExample()
	example.CreateCriteria().AndEqualTo("username", username)
	err := r.Mapper.SelectByExample(example, m)
	if err != nil {
		return nil, err
	}
	return m, nil
}

func (r *AccountRepositoryImpl) GetList(ctx context.Context) ([]*model.Account, error) {
	var m = make([]*model.Account, 0)
	err := r.Mapper.SelectAll(&m)
	if err != nil {
		return nil, err
	}
	return m, nil
}

func (r *AccountRepositoryImpl) Update(ctx context.Context, account *model.Account) (*model.Account, error) {
	err := r.DB.WithContext(ctx).Save(account).Error
	if err != nil {
		return nil, err
	}
	return account, nil
}
